package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import config.AlipayConfig;
import model.Order;
import service.OrderService;
import service.ShoppingcartService;
import service.impl.OrderServiceImpl;
import service.impl.ShoppingcartServiceImpl;
import utile.GenerateNum;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author gzp
 * @create 2022-12-14 12:54
 */
@WebServlet("/order/pay")
public class OrderPayServlet extends HttpServlet {
    OrderService orderService = new OrderServiceImpl();
    ShoppingcartService shoppingcartService = new ShoppingcartServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //解析前端并转为json类型
        BufferedReader reader = new BufferedReader(req.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = GenerateNum.generateOrder();
        //付款金额，必填
        String total_amount = String.valueOf(jsonObject.getDouble("total_amount"));
        //订单名称，必填
        String subject = jsonObject.getString("subjectName");

        int uid = jsonObject.getInteger("uid");

        Integer sid = jsonObject.getInteger("sid");

        Order order = new Order();
        order.setUid(uid);
        order.setSid(sid);
        Date date = new Date();
        order.setState(0);
        order.setTradeNo(out_trade_no);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String startString = formatter.format(date);
        java.sql.Date sDate =   java.sql.Date.valueOf(startString );
        order.setDate(sDate);

        JSONObject message = new JSONObject();

        if (!orderService.insert(order)) {
            message.put("state", 0);
            return;
        }
        shoppingcartService.delete(uid, String.valueOf(sid));
        alipayRequest.setBizContent(
                "{\"out_trade_no\":\"" + out_trade_no + "\"," +
                        "\"total_amount\":\"" + total_amount +
                        "\"," + "\"subject\":\"" + subject +
                        "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"
        );

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        //输出
        message.put("state", 1);
        message.put("result", result);
        resp.getWriter().write(message.toString());
    }
}
